<template>
    <view 
        class="zz-container zz-container_wallet_balance"
        :class="[[showWrap?'':'zz-hide'],[tabCurrentIndex===1?'zz-pb0_i':'']]">
        <!-- navBar -->
        <view class="zz-nav-wrap">
            <uni-navbar
                @tabClick="tabClick"
                :navList="navList"
                :tabCurrentIndex="tabCurrentIndex"
                :borderColor="themeStyles.lightMainColor"
            ></uni-navbar>
        </view>
        <!-- 总资产 -->
        <view 
            v-show="tabCurrentIndex==0"
            class="total-assets">
            <!-- 概览数据 -->
            <view class="zz-area zz-area_nobr zz-area_nobs main">
                <view class="zz-mb12 fs32 lh44 color333">账户余额</view>
                <view 
                    class="fs48 fs-bold lh58"
                    :style="themeStyles.textMainColor">{{balance}}</view>
                <view class="zz-flex zz-jc-fe">
                    <view 
                        v-for="(item,index) in dataType"
                        :key="index"
                        :class="[activeType==index?'color333':'color999']"
                        class="zz-flex_ele fs28 lh40"
                        @click="tabRecord(index)">
                        {{item.label}}
                        <!--  -->
                        <view 
                            v-if="index===0"
                            class="zz-jg_line zz-jg_line_bg zz-jg_line_v zz-jg_line_pos_r zz-jg_line_v_40"></view>
                    </view>
                </view>
            </view>
            <!-- 详情数据 -->
            <view class="detail">
                <!-- 消费记录 + 充值记录 -->
                <view
                    v-for="(info,k) in recordList"
                    :key="k"
                    v-show="k==activeType">
                    <!-- empty -->
                    <empty 
                        v-if="!info.data.length"
                        :src="`${baseTemplateFileUri}/image/emptyStatus/common.png`"
                        :desc="info.emptyText"></empty>
                    <!-- 列表 -->
                    <view 
                        v-for="(item,index) in info.data"
                        :key="index"
                        class="zz-area zz-area_mh160">
                        <view class="zz-flex zz-jc-sb zz-mb30 fs24 lh34 color333">
                            <view class="zz-flex-fb40">{{item.time}}</view>
                            <view class="zz-flex-fb60 fs22 zz-flex zz-jc-fe">{{item.orderId}}</view>
                        </view>
                        <view class="zz-flex zz-jc-sb zz-jc-sb">
                            <view class="zz-flex-fb70 fs28 lh40 color666">{{item.context}}</view>
                            <view class="fs32 lh38 color333 fs-bold">{{item.money}}</view>
                        </view>
                    </view>
                </view>
                <!--  -->
                <uni-load-more
                    v-if="recordList[activeType].data.length" 
                    :status="loadingType"> </uni-load-more>
                <!--  -->
                <!--  -->
                <!-- <view class="zz-area zz-area_mh160">
                    <view class="zz-flex zz-mb30 fs24 lh34 color333">
                        <view class="zz-flex-fb50">2020-08-20 11:37</view>
                        <view class="zz-flex-fb50 zz-flex zz-jc-fe">订单号:202007204567</view>
                    </view>
                    <view class="zz-flex zz-jc-sb">
                        <view class="zz-flex-fb70 fs28 lh40 color666">充值500送100元。</view>
                        <view class="fs32 lh38 color333 fs-bold">+600</view>
                    </view>
                </view> -->
            </view>
        </view>
        <!-- 付款码 -->
        <view v-show="tabCurrentIndex==1">
            <view class="paycode-area">
                <!--  -->
                <view class="paycode-qrcode">
                    <!-- 标题 -->
                    <view 
                        :style="themeStyles.backgroundMainColor"
                        class="paycode-qrcode_title zz-flex">
                        <text 
                            class="fs36 lh42 colorFFF template__icon template_icon-pay"></text>
                        <view class="zz-ml20 fs28 lh42 colorFFF">向商家付款</view>
                    </view>
                    <!-- 二维码 :style="themeStyles.backgroundMainColor" -->
                    <view class="paycode-qrcode_code">
                        <!--  -->
                        <image
                            :key="`${qrCodeSrcChange}`"
                            v-if="qrCodeSrcChange"
                            :src="`${qrCodeSrc}`"
                            class="zz-img-fit"></image>
                    </view>
                    <!--  -->
                    <view class="zz-flex zz-jc-c fs24 lh34 color999">付款码每30秒刷新一次</view>
                </view>
                <!--  -->
                <view class="paycode-discount">
                    <view 
                        class="zz-flex zz-flex_mh100 first zz-jc-sb zz-ai-c"
                        @click="couponVisible = true">
                        <view class="fs28 lh40 color333">优惠券</view>
                        <view class="fs28 lh40 color333">
                            <!-- showDiscountPrice(selectedCoupon.couponType) -->
                            <text>{{
                                !ZZisEmptyObject(selectedCoupon)?showDiscountPrice(selectedCoupon.couponType,selectedCoupon):"选择优惠券"
                            }}</text>
                            <text class="zz-ml12 template__icon template__icon-right"></text>
                        </view>
                        <!--  -->
                        <view class="zz-jg_line zz-jg_line_h zz-jg_line_pos_lb zz-jg_line_bg"></view>
                    </view>
                    <view class="zz-flex zz-flex_mh100 zz-jc-sb zz-ai-c">
                        <view class="fs28 lh40 color333">会员折扣</view>
                        <view class="fs28 lh40 color333">{{customerLevel.discount?customerLevel.discount+'折':'暂无'}}</view>
                    </view>
                </view>
            </view>
        </view>
        <!-- 底部按钮区域 -->
        <view 
            v-show="tabCurrentIndex==0"
            class="footer footer_ye">
            <button 
                type="primary"
                class="btn size full"
                :style="themeStyles.btnFullColor"
                @click="goToRecharge">立即充值</button>
        </view>
		<!-- 选择优惠券弹层 -->
		<pop-bottom
			:visible="couponVisible"
			@close="couponVisible=false">
            <!-- 标题 -->
            <template slot="title">
                <view 
                    v-if="couponList.length" 
                    class="fs32 lh44 color333">请确定付款金额达到优惠门槛</view>
            </template>
            <!-- 内容 -->
            <template slot="content">
                <!-- empty -->
                <empty 
                    v-if="!couponList.length"
                    :src="`${baseTemplateFileUri}/image/emptyStatus/common.png`"
                    desc="暂无可使用的优惠券~~"></empty>
                <view>
                    <coupon-item
                        v-for="(item,index) in couponList"
                        :key="index"
                        :index="index"
                        :selected="item.selected"
                        :couponInfo="item"
                        @change-status="changeCouponStatus"
                        @select-coupon="getCoupon"></coupon-item>   
                </view>    
            </template>
            <!-- 按钮 -->
            <template slot="footer">
                <view
                    v-if="couponList.length&&!ZZisEmptyObject(selectedCoupon)" 
                    class="footer footer_ye zz-jc-c zz-ai-c">
                    <view
                        @click.stop="resetCouponStatus"
                        :style="themeStyles.btnFullColor"
                        class="zz-flex-10auto zz-btn zz-btn_popBotton"
                    >取消使用优惠券</view>
                </view>
            </template>
        </pop-bottom>
        <!-- 提示弹层 -->
		<!-- 扫码支付余额不足提示弹层 -->
		<notice
            :visible="noticeVisible"
            @close="noticeVisible=false">
            <!-- 标题 -->
            <template slot="header">
                <view class="zz-mb50">余额不足 付款失败</view>
            </template>
            <!--  -->
            <view slot="body">
                <view class="zz-flex zz-jc-c zz-mb32 fs32 lh44 color333">
                    <text>付款金额：</text>
                    <text>{{noticeData.totalFee}}</text>
                </view>
                <view class="zz-flex zz-jc-c zz-mb32 fs32 lh44 color333">
                    <text>当前余额：</text>
                    <text>{{noticeData.moneyTotal}}</text>
                </view>
                <view class="zz-flex zz-jc-c zz-mb60 fs32 lh44 color333">
                    <text>至少充值：</text>
                    <text>{{noticeData.fillMoney}}</text>
                </view>
            </view>
            <!--  -->
            <view slot="footer">
                <view 
                    @click="goToRechargeByFill"
                    :style="themeStyles.btnPrimary"
                    class="zz-btn zz-btn_large">立即充值</view>
            </view>
        </notice>
    </view>
</template>
<script>
const app = getApp();
/* api -------- begin */
import {
    _customerMoneyRecord,  //买家端余额变动记录
    _manageFillRecord,     //充值记录
    _getQR,  //获取支付二维码图片
    _socketUrl  //socket地址
} from "@/lib/api/walletServer/info"; 
import {
    queryMyCouponList  //获取我的优惠券
} from "@/lib/api/couponServer/customer";
import {
    queryCustomerLever  //等级客户等级信息
} from "@/lib/api/customerServer/level";
/* api --------end */
/* minxin */
import walletMixin from "@/mixins/wallet";
import socketMixin from "@/mixins/socket";
/* navbar组件 */
import uniNavbar from "@/components/uniNavbar/uniNavbar";
/*  */
import uniLoadMore from "@/components/uniLoadMore/uniLoadMore";
/* 列表数据为空的时候--组件 */
import empty from "@/components/empty";
/* 卡片项 */
import couponItem from "@/components/coupon/couponItem";
/* 底部弹出层 */
import popBottom from "@/components/popBottom";
/* 提示弹层 */
import notice from "@/components/notice";
/* vuex */
import { mapState,mapMutations } from "vuex";
export default {
    mixins:[
        walletMixin,
        socketMixin
    ],
    components:{
        uniNavbar,
        uniLoadMore,
        empty,
        couponItem,
        popBottom,
        notice
    },
    computed:{
        ...mapState("login",["userInfo"]),
        ...mapState("wallet",["balance","customerLevel"]),
        ...mapState("coupon",["couponTypes"]),
        /* qrCodeSrc(){
            return `${_getQR()}${this.userInfo.customerId}`
        } */
    },
    data(){
        return {
            /*  */
            loadingType:"more",
            /*  */
            noticeVisible:false, //余额不足提示弹层
            noticeData:{
                totalFree:"",  //付款金额
                moneyTotal:"",  //当前余额
                fillMoney:""   //至少充值
            },
            /* 显示页面 */
            showWrap:false,
            /*  */
            couponVisible:false, //选择优惠券弹层
            couponList:[], //我的优惠券
            selectedCoupon:{},  //选中的优惠券
            /* navList */
            tabCurrentIndex:0,
            navList:[
                {
                    text:"总资产"
                },
                {
                    text:"付款码"
                }
            ],
            /*  */
            activeType:0,
            dataType:[
                {
                    label:"消费记录",
                    value:"10"
                },
                {
                    label:"充值记录",
                    value:"20"
                }
            ],
            /* 消费记录 + 充值记录 数据 */
            recordList:[
                {
                    name:"消费记录",
                    type:"10",
                    data:[],
                    total:0, //总数
                    currentPage:1,
                    emptyText:"暂无消费记录喔~"
                },
                {
                    name:"充值记录",
                    type:"20",
                    data:[],
                    total:0, //总数
                    currentPage:1,
                    emptyText:"暂无充值记录喔~"
                }
            ]
        }
    },
    created(){
        //console.log(this.qrCodeSrc);
        //
        //console.log("---userInfo---",this.userInfo);
        //console.log(`${_getQR()}${this.userInfo.customerId}`);
    },
    /*  */
    onLoad(){
    },
    /* 关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】 */
    beforeDestroy(){
        //this.closeSocket();
    },
    /*  */
    onHide(){
        
    },
    /*  */
    onUnload(){
        app.globalData.closeBalancePage = true;
        //this.socketTask.close();
        this.closeSocket();
    },
    /*  */
    async onShow(){
        /* s */
        this.socketUrl = `${_socketUrl}${this.userInfo.customerId}`;
        console.log("---socketUrl---",this.socketUrl);
        this.initSocket(
            this.socketUrl,
            ()=>{
                return `${_getQR()}${this.userInfo.customerId}`;
            },
            async (data)=>{
                //刷新支付二维码
                this.refreshPayQrcode();
                //支付结果
                if(data.type=="10"){
                    //扫码支付成功
                    if(data.result){
                        //
                        await this._getWallet();
                        //
                        this.loginNavTo(`/pages/user/pages/wallet/paySuccess?info=${JSON.stringify(data)}`);
                    }else{
                        //支付失败
                        this.noticeData = null;
                        this.noticeData = data;
                        //
                        this.noticeVisible = true;
                    }
                }
            }
        );
        /* e */
        //
        this.showWrap = true;
        this.tabCurrentIndex = 0;
        this.activeType = 0;
        //
        //从首页“付款码”跳转来
        //console.log(app.globalData.fromIndexQrcodeToBalance);
        if(app.globalData.fromIndexQrcodeToBalance){
            app.globalData.fromIndexQrcodeToBalance = false;
            this.tabCurrentIndex = 1;
        }
        //从充值页面返回--点击充值按钮
        if(app.globalData.fromRechargePageToRechargeBtn){
            app.globalData.fromRechargePageToRechargeBtn = false;
            this.tabCurrentIndex = 0;
            this.activeType = 1;
        }
        //从充值页面返回--二维码付款余额不足
        if(app.globalData.fromRechargePageToQrcodeFillMoney){
            console.log("app.globalData.fromRechargePageToQrcodeFillMoney");
            app.globalData.fromRechargePageToQrcodeFillMoney = false;
            this.tabCurrentIndex = 1;
            this.activeType = 1;
        }
        //获取余额信息
        await this._getWallet();
        //获取充值和消费记录
        await this.pageContentRefresh();
        //获取我的优惠券
        await this.getMyCoupons();
        // 获取客户等级信息
        const resCL = await queryCustomerLever();
        //console.log(resCL);
        this.setCustomerLevel(resCL.data);
    },
    /* 下拉刷新 */
    async onPullDownRefresh(){
        if(this.tabCurrentIndex!==0)return;
        //
        await this.pageContentRefresh();
        uni.stopPullDownRefresh({
            complete:()=>{}
        })
    },
    /* 上拉加载 */
    onReachBottom(){
        if(this.tabCurrentIndex!==0)return;
        this._customerMoneyRecord();
    },
    methods:{
        /*  */
        ...mapMutations("wallet",["setBalance", "setCustomerLevel"]),
        /* 
            选择不同类型的优惠券后展示优惠金额
        */
        showDiscountPrice(type,couponInfo){
            if(!type)return "";
            const coupon = this.couponTypes[`${type}`];
            if(!coupon)return "-----";
            return `${coupon.symbolBefore}${coupon.calc?coupon.symbol:""}${coupon.calc?this.ZZaddNumZero(couponInfo.discounts):couponInfo.discounts*0.1}${coupon.symbolAfter}`;
        },
        /* 
            跳转到充值页面---二维码付款余额不足
        */
        goToRechargeByFill(){
            //
            this.noticeVisible=false;
            //
            app.globalData.fromQrcodeFillMoneyToRechargePage = true;
            //
            this.loginNavTo(`/pages/user/pages/wallet/recharge`);
        },
        /* 跳转到充值页面---点击充值按钮 */
        goToRecharge(){
            //
            app.globalData.fromRechargeBtnToRechargePage = true;
            //
            this.loginNavTo('/pages/user/pages/wallet/recharge');
        },
        /* 列表数据重载 */
        async pageContentRefresh(){
            this.recordList[this.activeType].currentPage = 1;
            this.recordList[this.activeType].data = null;
            this.recordList[this.activeType].data = [];
            //
            await this._customerMoneyRecord();
        },
        /* tab切换 */
        tabClick(index){
            this.tabCurrentIndex = index;
            //
            if(this.tabCurrentIndex===0&&!this.recordList[this.activeType].data.length){
                this.pageContentRefresh();
            }
        },
        /* 切换记录 */
        tabRecord(index){
            //console.log(index);
            if(this.activeType == index)return;
            //
            this.activeType = index;
            //
            if(!this.recordList[this.activeType].data.length){
                this.pageContentRefresh();
            }
            //
            this.ZZscrollTop();
        },
        /* 获取记录数据 */
        _customerMoneyRecord(){
            //
            if(this.recordList[this.activeType].data.length&&this.recordList[this.activeType].data.length===this.recordList[this.activeType].total){
                this.loadingType = "noMore";
                return Promise.resolve();
            }else{
                this.loadingType = "more";
            }
            //
            let currentPage = this.recordList[this.activeType].currentPage;
            return _customerMoneyRecord({
                currentPage,
                showLoading:false,
                type:this.recordList[this.activeType].type
            }).then(res=>{
                console.log(res);
                if(res.data.list.length){
                    res.data.list.forEach(item=>{
                        this.recordList[this.activeType].data.push(item);
                    });
                    this.recordList[this.activeType].total = res.data.total;
                    this.recordList[this.activeType].currentPage+=1;
                }
                //
                if(this.recordList[this.activeType].data.length === this.recordList[this.activeType].total){
                    this.loadingType = "noMore";
                }
            }).catch(err=>{
                this.$api.showModal({
                    content:`获取${this.recordList[this.activeType].name}数据失败`
                });
            });
        },
        /* 获取我的优惠券 */
        async getMyCoupons(){
            let couponRes = await queryMyCouponList({
                showLoading:false,
                availableStatus:"0"  //待使用的优惠券
            });
            // console.log(couponRes);
            this.couponList = null;
            this.couponList = couponRes.data.list;
            this.couponList.forEach(item=>{
                this.$set(item,"selected",false);
            });
        },
        /* 清空卡片选中 */
        initCouponList(){
            if(this.couponList){
                this.couponList.forEach(item=>{
                    this.$set(item,"selected",false)
                });
            }
            this.selectedCoupon = null;
            this.selectedCoupon = {};
        },
        /* 修改卡片的选选中状态 */
        changeCouponStatus(index){
            this.initCouponList();
            //
            this.$set(this.couponList[index],"selected",true);
        },
        /* 清空卡片选中状态--并推数据到后台 */
        resetCouponStatus(){
            this.initCouponList();
            //向后台推送数据---取消选择优惠券
            this.socketTask.send({
                data:JSON.stringify({
                    "type": -10,
                    "customerId": this.userInfo.customerId,
                    "couponCustomerId": "",
                }),
                async success() {
                    console.log("取消选择优惠券--消息发送成功");
                },
            });
            //
            this.couponVisible = false;
        },
        /* 选择优惠券--并推数据到后台 */
        getCoupon(info,index){
            //console.log(info);
            this.selectedCoupon = null;
            this.selectedCoupon = info;
            console.log(this.selectedCoupon);
            //向后台推送数据---选择优惠券
            this.socketTask.send({
                data:JSON.stringify({
                    "type": -10,
                    "customerId": this.userInfo.customerId,
                    "couponCustomerId": this.selectedCoupon.couponCustomerId,
                }),
                async success() {
                    console.log("选择优惠券--消息发送成功");
                },
            });
            //
            this.couponVisible = false;
        }
    }
}
</script>
<style lang="scss">
/*  */
@import "@/common/styles/order/order.scss";
/*  */
.zz-container_wallet_balance {
    padding-top:88rpx;
    padding-bottom:120rpx;
    .total-assets {
        min-height:100vh;
    }
    /* 余额一览 */
    .main {
        position:fixed;
        top:86rpx;
        left:0;
        width:100%;
        height:224rpx;
        padding:52rpx 0rpx 24rpx 40rpx;
        z-index:999;
        .zz-flex_ele {
            padding:0rpx 32rpx;
        }
    }
    /* 详情数据 */
    .detail {
        padding:252rpx 24rpx 0rpx;
        .zz-area {
            margin-bottom:24rpx;
            padding:28rpx 24rpx;
        }
    }
    /* 付款码 */
    .paycode-area {
        /* margin-top:86rpx; */
        padding:60rpx 32rpx 0rpx;
        min-height:calc(100vh - 86rpx);
        background-color:#F4F4F4;
    }
    .paycode-qrcode {
        height:760rpx;
        margin-bottom:40rpx;
        border-radius:16rpx;
        background-color:#fff;
    }
    .paycode-qrcode_title {
        height:92rpx;
        padding:28rpx 0rpx 0rpx 24rpx;
        border-radius:16rpx 16rpx 0rpx 0rpx;
        background-color:#F5F5F5;
    }
    .paycode-qrcode_code {
       width:433rpx; 
       height:421rpx;
       margin:90rpx auto 78rpx; 
    }
    /* 选择优惠券 */
    .paycode-discount {
        padding:0rpx 24rpx;
        border-radius:16rpx;
        background-color:#fff;
    }
}
</style>